//
//  HJHomeDetailController.m
//  Sneakers
//
//  Created by 胡光健 on 2017/9/20.
//  Copyright © 2017年 mac. All rights reserved.
//

#import "HJHomeDetailController.h"
#import "HJHeaderView.h"
#import "HJHomeDetailCell.h"
#import "HJHomeDetailListCell.h"
#import "HJHomeDetailBottom.h"
#import "HJSubmitOderViewController.h"
#import "HJSellOderViewController.h"
#import "HJHomeModel.h"
#import "HJShareView.h"

@interface HJHomeDetailController ()<UIScrollViewDelegate> {
    NSInteger _currentTag;
    HJHeaderView * _header;
    NSInteger _cellHeight;
    BOOL _cellBool;
    NSString * _size;
    NSString * _cost;
    NSString * _dellCount;
    NSString * _sellCount;
    NSString * _buyCount;
    HJHomeDetailBottom *_detailBottom;
}
@property(nonatomic,strong)HJUserModel * infoModel;
@property(nonatomic,strong)HJHomeModel * shoesModel;
@property(nonatomic,strong) NSArray * daysArr;
@property(nonatomic,strong) NSArray * shoesSizeArr;

@property(nonatomic,strong) NSMutableArray<HJHomeDetailModel *>* shoesSellArr;
@property(nonatomic,strong) NSMutableArray<HJHomeDetailModel *>* shoesBuyArr;
@property(nonatomic,strong) NSMutableArray<HJHomeDetailModel *>* shoesListArr;
@end

@implementation HJHomeDetailController

-(NSArray *)shoesSizeArr {
    if (!_shoesSizeArr) {
        _shoesSizeArr = [NSArray array];
    }
    return _shoesSizeArr;
}

-(NSArray *)daysArr {
    if (!_daysArr) {
        _daysArr = [NSArray array];
    }
    return _daysArr;
}

-(NSMutableArray<HJHomeDetailModel *> *)shoesSellArr {
    if (!_shoesSellArr) {
        _shoesSellArr = [NSMutableArray array];
    }
    return _shoesSellArr;
}

-(NSMutableArray<HJHomeDetailModel *> *)shoesBuyArr {
    if (!_shoesBuyArr) {
        _shoesBuyArr = [NSMutableArray array];
    }
    return _shoesBuyArr;
}

-(NSMutableArray<HJHomeDetailModel *> *)shoesListArr {
    if (!_shoesListArr) {
        _shoesListArr = [NSMutableArray array];
    }
    return _shoesListArr;
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
//    [[self.navigationController.navigationBar subviews] objectAtIndex:0].alpha = 1;
    [self navigationAlpha];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
//    [[self.navigationController.navigationBar subviews] objectAtIndex:0].alpha = 0;
    [self navigationWithAlpha];

    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(cellHeightNotification:) name:@"cellHeightNotification" object:nil];
}

-(void)cellHeightNotification:(NSNotification *)not {
    _cellHeight = [not.userInfo[@"cellHeight"] integerValue];
    _cellBool = [not.userInfo[@"bool"] integerValue];
    [self.tableView reloadData];
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.infoModel = [HJUserManager getUserModel];
    self.rightNavImageName = @"Fill 2";
    self.leftNavImageName = @"Fill 1";
    [self loadNetworkData];
    _cellBool = YES;
    self.shoesModel = [[HJHomeModel alloc]init];
    [self configBottomView];
    self.navigationController.navigationBar.backgroundColor = [UIColor clearColor];
    
}

-(void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if (scrollView.contentOffset.y >= 200) {
        [self navigationAlpha];
    }else {
        [self navigationWithAlpha];
    }
}
-(void)navigationWithAlpha {
    [self.navigationController.navigationBar setBackgroundImage:[UIImage new] forBarMetrics:UIBarMetricsDefault];
    self.navigationController.navigationBar.shadowImage = [UIImage new];
    self.navigationController.navigationBar.translucent = YES;
    self.navigationController.navigationBar.layer.shadowColor = HJColorRGB(255).CGColor;
    self.navigationController.navigationBar.layer.shadowOffset = CGSizeZero;
    self.navigationController.navigationBar.layer.shadowRadius = 0;
    self.navigationController.navigationBar.layer.shadowOpacity = 0;
}
-(void)navigationAlpha {
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageWithColor:HJColorRGB(255)]  forBarMetrics:UIBarMetricsDefault];
    self.navigationController.navigationBar.shadowImage = [UIImage imageWithColor:HJColorRGB(255)];
    self.navigationController.navigationBar.translucent = NO;
    self.navigationController.navigationBar.layer.shadowColor = HJColorRGB(0).CGColor;
    self.navigationController.navigationBar.layer.shadowOffset = CGSizeZero;
    self.navigationController.navigationBar.layer.shadowRadius = 3;
    self.navigationController.navigationBar.layer.shadowOpacity = 0.25;
}

-(void)configTableView {
    self.needRefresh = YES;
    self.tableViewStyle = UITableViewStylePlain;
    [super configTableView];
    CGFloat H;
    if (mScreenHeight<812) {
         H = mScreenHeight-60;
    }else {
        H = mScreenHeight-60-X_Bottom_Space;
    }
    self.tableView.frame = CGRectMake(0, -NavBar_H, mScreenWidth, H);
    self.tableView.tableHeaderView = [self configHeaderView];
    [self.tableView registerCellByNibName:@"HJHomeDetailCell"];
    [self.tableView registerCellByNibName:@"HJHomeDetailListCell"];
}
//分享
-(void)didClickRightNavAction {
    self.needAlert = YES;
    self.backView.hidden = NO;
    self.shareView.hidden = NO;
    
}
-(void)shareBtnWithTag:(NSInteger)tag {
    self.needAlert = NO;
    self.backView.hidden = YES;
    self.shareView.hidden = YES;
    
    NSString * title = _header.model.shoes_name;
    NSString *content =[NSString stringWithFormat:@"￥%@",_header.model.reference_price];
    
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"shoes_id"] = self.shoes_id;
    params[@"size"] = _size;
    NSString * parmasStr = [TZHttpTool keyValueStringWithParams:params];
    NSString * shareURL = [NSString stringWithFormat:@"%@%@",@"http://app.ttouch.com.cn/sneaker/sneaker_home/index.html",parmasStr];
    NSLog(@"%@",shareURL);
    NSString *imageUrl = [NSString stringWithFormat:@"%@/%@",_header.model.avatar_base_url,_header.model.avatar_path];
    
    switch (tag) {
        case 100:
            if (![QQApiInterface isQQInstalled]) {
                [self showSuccessHUDWithStr:@"您尚未安装QQ"];
            } else {
                [[HJShareManager manager] share:SSDKPlatformSubTypeQQFriend title:title content:content url:shareURL imageUrlStr:imageUrl];
            }
            break;
        case 101:
            if (![WeiboSDK isWeiboAppInstalled]) {
                [self showSuccessHUDWithStr:@"您尚未安装微博"];
            }else {
                [[HJShareManager manager] share:SSDKPlatformTypeSinaWeibo title:title content:content url:shareURL imageUrlStr:imageUrl];
            }
            break;
        case 102:
            if (![WXApi isWXAppInstalled]) {
                [self showSuccessHUDWithStr:@"您尚未安装微信"];
            } else{
                [[HJShareManager manager] share:SSDKPlatformSubTypeWechatSession title:title content:content url:shareURL imageUrlStr:imageUrl];
            }
            break;
        case 103:
            if (![WXApi isWXAppInstalled]) {
                [self showSuccessHUDWithStr:@"您尚未安装微信"];
            } else{
                 [[HJShareManager manager] share:SSDKPlatformSubTypeWechatTimeline title:title content:content url:shareURL imageUrlStr:imageUrl];
            }
            break;
        default:
            break;
    }
}
-(void)cancelBtn {
    self.needAlert = NO;
    self.backView.hidden = YES;
    self.shareView.hidden = YES;
}
-(void)didClickLeftNavAction {
    [self.navigationController popViewControllerAnimated:YES];
}

-(UIView *)configHeaderView {
    _header = [[HJHeaderView alloc]initWithFrame:CGRectMake(0, 0, mScreenWidth, 320)];
    return _header;
}

-(void)configBottomView {
    UIView * view = [[UIView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(self.tableView.frame), self.tableView.width, 60)];
    [self.view addSubview:view];
    MJWeakSelf;
    _detailBottom = [[NSBundle mainBundle] loadNibNamed:@"HJHomeDetailBottom" owner:self options:nil].firstObject;
    _detailBottom.frame = CGRectMake(0, 0, mScreenWidth, 60);
    _detailBottom.buyOrsellBlock = ^(NSInteger tag) {
        for (NSDictionary * dic in weakSelf.shoesSizeArr) {
            if ([dic[@"check"] isEqual:@1]) {
                _size = dic[@"size"];
                break;
            }
        }
        if (_size.length<1) {
            [weakSelf showHint:@"请选择尺码"];
            return;
        }
        if (tag==100) {// 购买
            NSNumber * num;
            if (_detailBottom.begBuy.hidden == YES) {
                num=@101;// 求购
            }else {
                num= @100;// 购买
            }
            [weakSelf pushWithSubmitOder:_header.model.shoes_id size:_size type:@2 currentPush:num];
        }else {
            [weakSelf pushWithSellOder:_header.model.shoes_id size:_size type:@1 currentPush:@100];
        }
    };
    [view addSubview:_detailBottom];
}

-(void)loadNetworkData {
    NSMutableDictionary * params = [NSMutableDictionary dictionary];
    params[@"page"] = @(self.page);
    params[@"shoes_id"] = self.shoes_id;
    params[@"size"] = _size;
    [TZHttpTool post:ShoesDetailAPI params:params success:^(NSDictionary *result) {
        _header.model = [HJHomeModel mj_objectWithKeyValues:result[@"data"][@"shoes"]];
        if (self.page==1) {
            [self.shoesListArr removeAllObjects];
            [self.shoesSellArr removeAllObjects];
            [self.shoesBuyArr removeAllObjects];
        }
       
        self.daysArr = result[@"data"][@"seven_days2"];
        self.shoesSizeArr = result[@"data"][@"shose_size"];
        NSString * lastcoste = result[@"data"][@"last_cost"];
        dispatch_async(dispatch_get_main_queue(), ^{
            if ([lastcoste isEqualToString:@""]) {
                _detailBottom.moneyLabel.text = @"￥0.00";
            }else {
                _detailBottom.moneyLabel.text = [NSString stringWithFormat:@"￥%@",lastcoste];
            }
        });
        self.totalPage = result[@"data"][@"deal"][@"totalPage"];
        _dellCount= result[@"data"][@"deal"][@"count"];
        _sellCount= result[@"data"][@"sell_shoes"][@"count"];
        _buyCount = result[@"data"][@"want_buy_shoes"][@"count"];
        NSArray * dealArr = [HJHomeDetailModel mj_objectArrayWithKeyValuesArray:result[@"data"][@"deal"][@"models"]];
        NSArray * sellArr = [HJHomeDetailModel mj_objectArrayWithKeyValuesArray:result[@"data"][@"sell_shoes"][@"models"]];
        NSArray * buyArr = [HJHomeDetailModel mj_objectArrayWithKeyValuesArray:result[@"data"][@"want_buy_shoes"][@"models"]];
        
        [self.shoesListArr addObjectsFromArray:dealArr];
        [self.shoesSellArr addObjectsFromArray:sellArr];
        [self.shoesBuyArr addObjectsFromArray:buyArr];
        [self.tableView endRefresh];
        [self.tableView reloadData];
        
    } failure:^(NSString *msg) {
        [self showErrorHUDWithError:msg];
    }];
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    if (_currentTag==12) {
        return self.shoesSellArr.count+1;
    }else if (_currentTag==11) {
        return self.shoesBuyArr.count+1;
    }else {
        return self.shoesListArr.count+1;
    }
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row==0) {
        HJHomeDetailCell * homeDetailCell = [tableView dequeueReusableCellWithIdentifier:@"HJHomeDetailCell"];
        homeDetailCell.selectionStyle = UITableViewCellSelectionStyleNone;
        homeDetailCell.cellBool = _cellBool;
        homeDetailCell.daysArr = self.daysArr;
        homeDetailCell.shoesSizeArr = self.shoesSizeArr;
        [homeDetailCell.clinchadealBtn setTitle:[NSString stringWithFormat:@"成交记录(%@)",_dellCount] forState:UIControlStateNormal];
        [homeDetailCell.sellBtn setTitle:[NSString stringWithFormat:@"出售列表(%@)",_sellCount] forState:UIControlStateNormal];
        [homeDetailCell.buyBtn setTitle:[NSString stringWithFormat:@"求购列表(%@)",_buyCount] forState:UIControlStateNormal];
        WeakSelf
        homeDetailCell.collectionWithSizeBlock = ^(NSString *size, NSString * cost) {
            _size = size;
            _cost = cost;
            if ([cost isEqualToString:@""]) {
                [_detailBottom.buyBtn setTitle:@"求购" forState:UIControlStateNormal];
            }else {
                [_detailBottom.buyBtn setTitle:@"购买" forState:UIControlStateNormal];
               
            }
            [weakSelf loadNetworkData];
            
        };
        homeDetailCell.block = ^(NSInteger tag) {
            _currentTag = tag;
            [weakSelf.tableView reloadData];
        };
        return homeDetailCell;
    }else {
        HJHomeDetailListCell * homeDetaiListCell = [tableView dequeueReusableCellWithIdentifier:@"HJHomeDetailListCell"];
        homeDetaiListCell.selectionStyle = UITableViewCellSelectionStyleNone;
        [homeDetaiListCell skipImageWithIndex:_currentTag ? _currentTag :10];
        homeDetaiListCell.index = _currentTag ? _currentTag :10;
        if (_currentTag==12) {
            homeDetaiListCell.model = self.shoesSellArr[indexPath.row -1];
            homeDetaiListCell.stauteLabel.text = @"出售价";
        }else if (_currentTag==11) {
            homeDetaiListCell.model = self.shoesBuyArr[indexPath.row -1];
            homeDetaiListCell.stauteLabel.text = @"求购价";
        }else {
            homeDetaiListCell.model = self.shoesListArr[indexPath.row -1];
            homeDetaiListCell.stauteLabel.text = @"成交价";
        }
        return homeDetaiListCell;
    }
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row==0) {
        return _cellBool ? (mScreenWidth -6*2.5)/5.0 +5 +300 : _cellHeight +20;
    }else {
        return 62;
    }
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row==0) {
        return;
    }
    if (_currentTag==11) {
        HJHomeDetailModel * model = self.shoesBuyArr[indexPath.row -1];
        [self pushWithSellOder:model.shoes_id size:model.shoes_size type:@1 currentPush:@101];
    }else if (_currentTag==12) {
        HJHomeDetailModel * model = self.shoesSellArr[indexPath.row -1];
        [self pushWithSubmitOder:model.shoes_id size:model.shoes_size type:@2 currentPush:@100];
    }else{
        return;
    }
}

-(void)pushWithSubmitOder:(NSString * )shoes_id size:(NSString *)size type:(NSNumber*)type currentPush:(NSNumber *)currentPush {
    HJSubmitOderViewController *submitOderVC = [[HJSubmitOderViewController alloc]init];
    submitOderVC.shoes_size = size;
    submitOderVC.shoes_id = shoes_id;
    submitOderVC.type = type;
    submitOderVC.navTitle = @"提交订单";
    submitOderVC.currentPush = currentPush;
    submitOderVC.cost = _cost;
    [self.navigationController pushViewController:submitOderVC animated:YES];
}

-(void)pushWithSellOder:(NSString * )shoes_id size:(NSString *)size type:(NSNumber*)type currentPush:(NSNumber *)currentPush {
    HJSellOderViewController *sellOderVC= [[HJSellOderViewController alloc]init];
    sellOderVC.navTitle = @"提交订单";
    sellOderVC.shoes_size = size;
    sellOderVC.shoes_id = shoes_id;
    sellOderVC.type = type;
    sellOderVC.currentPush = currentPush;
    [self.navigationController pushViewController:sellOderVC animated:YES];
}
@end
